<?php

namespace app\admin\controller;

use app\admin\model\BydAgreement;
use app\admin\model\BydDesignerArea;
use app\admin\model\Bydletter;
use app\common\controller\Backend;
use app\common\controller\News;
use think\db;
/**
 * 楼盘独家经营权申请
 *
 * @icon fa fa-circle-o
 */
class SoleAgency extends Backend
{
    
    /**
     * SoleAgency模型对象
     * @var \app\admin\model\SoleAgency
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SoleAgency;
        $this->view->assign("stateList", $this->model->getStateList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $buli=\app\admin\model\SoleBuilding::where('id',$row['bid'])->find();
                if($row['sole_type']==2){
                    if($params['state']==1){
                        $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->update(['status'=>1]);
                            $content='您的区域独家经营权申请已通过';
                            $update=\app\admin\model\BydDesignerArea::where('id',$row['bid'])->update(['did'=>$row['user_id']]);
                        $add=new Bydletter();
                        $add->data([
                            'user_id'=>$row['user_id'],
                            'orderid'=>0,
                            'content'=>$content,
                            'zt'=>'签约结果',
                            'state'=>0
                        ]);
                        $add->save();
                        $user=\app\admin\model\BydUser::find($row['user_id']);
                        $arr=[
                            'openid'=>$user['openid'],
                            'thing2'=>"您的区域独家经营权申请已通过",//$data['news'],
                            'thing6'=>"请前往小程序查看",

                        ];
                        $new=new News();
                        $news=$new->vr($arr);
//                        $useragfind=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->find();
//                        if(!empty($useragfind)){

//                            $qu=BydDesignerArea::where('id',$buli['area_id'])->find();
//                            $shi=BydDesignerArea::where('id',$qu['pid'])->find();
//                            $sheng=BydDesignerArea::where('id',$shi['pid'])->find();
//                            $agment=BydAgreement::where('id',$useragfind['agid'])->find();

                            // $bbsreal=BydUserSale::where('user_id',$row['userid'])->find();
//            if(!empty($des)){
                            $name=$row['username'];
//            }else{
//                $name='乙方';
//            }
//                            $startime= date ( 'Y-m-d' );
//                            $endtime=date ( 'Y-m-d' , strtotime ( '+364 day' ));
//                            $arrs=$agment['content'];
//                            $arrs=str_replace('{$name}',$name,$arrs);
//                            $arrs=str_replace('{$star}',$startime,$arrs);
//                            $arrs=str_replace('{$end}',$endtime,$arrs);
//                            $arrs=str_replace('{$sheng}',$sheng['title'],$arrs);
//                            $arrs=str_replace('{$shi}',$shi['title'],$arrs);
//                            $arrs=str_replace('{$qu}',$qu['title'],$arrs);
//                            $arrs=str_replace('{$lp}',$row['bname'],$arrs);
//                            $content=$arrs;
//                            $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->limit(1)->update(['status'=>1,'content'=>$content]);

//                        }
                    }elseif($params['state']==2){

                            $content='您的区域独家经营权申请已被驳回';
                            $update=\app\admin\model\BydDesignerArea::where('id',$row['bid'])->update(['did'=>0]);
                        $add=new Bydletter();
                        $add->data([
                            'user_id'=>$row['user_id'],
                            'orderid'=>0,
                            'content'=>$content,
                            'zt'=>'签约结果',
                            'state'=>0
                        ]);
                        $add->save();
                        $user=\app\admin\model\BydUser::find($row['user_id']);
                        $arr=[
                            'openid'=>$user['openid'],
                            'thing2'=>"您的区域独家经营权申请已被驳回",//$data['news'],
                            'thing6'=>"请前往小程序查看",

                        ];
                        $new=new News();
                        $news=$new->vr($arr);
                    }
                }else{
                    if($params['state']==1){
                        $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->where('lpid',$row['bid'])->update(['status'=>1]);
                        $useragfind=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->find();

                        $qu=BydDesignerArea::where('id',$buli['area_id'])->find();
                        $shi=BydDesignerArea::where('id',$qu['pid'])->find();
                        $sheng=BydDesignerArea::where('id',$shi['pid'])->find();
                        $agment=BydAgreement::where('id',$useragfind['agid'])->find();
                         if($row['sole_type']==1){
                             $bbsreal=\app\admin\model\BydDesigner::where('user_id',$row['user_id'])->find();
                             $nameqw=$bbsreal['username'];
                             $idcar=$bbsreal['idcart'];
                             $names="$nameqw$idcar";
                             $name=$bbsreal['username'];
                         }else{
                             $bbsreal=\app\admin\model\BydUserSale::where('user_id',$row['user_id'])->find();
                             $nameqw=$bbsreal['name'];
                             $idcar=$bbsreal['idcart'];
                             $names="$nameqw$idcar";
                             $name=$bbsreal['name'];
                         }
                         $bu=\app\admin\model\SoleBuilding::find($row['bid']);

//            if(!empty($des)){

//            }else{
//                $name='乙方';
//            }
                        $startime= date ( 'Y-m-d' );
                        $endtime=date ( 'Y-m-d' , strtotime ( '+364 day' ));
                        $arrs=$agment['content'];
                        $arrs=str_replace('{$name}',$names,$arrs);
                        $arrs=str_replace('{$standard}',$bu['standard'],$arrs);//交付标准
                        $arrs=str_replace('{$trun_time}',$bu['trun_time'],$arrs);//交付时间
                        $arrs=str_replace('{$oname}',$name,$arrs);
                        $arrs=str_replace('{$star}',$startime,$arrs);
                        $arrs=str_replace('{$end}',$endtime,$arrs);
                        $arrs=str_replace('{$sheng}',$sheng['title'],$arrs);
                        $arrs=str_replace('{$shi}', $shi['title'],$arrs);
                        $arrs=str_replace('{$qu}',$qu['title'],$arrs);
                        $arrs=str_replace('{$lp}',$row['bname'],$arrs);
                        $content=$arrs;
                        $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->limit(1)->update(['status'=>1,'content'=>$content]);
                        if($row['sole_type']==0){

                            $content='您的美居独家经营权申请已通过';
                            $update=\app\admin\model\SoleBuilding::where('id',$row['bid'])->update(['sign_bid'=>$row['user_id']]);
                        }else{
                            $update=\app\admin\model\SoleBuilding::where('id',$row['bid'])->update(['sign_did'=>$row['user_id']]);
                            $content='您的美居独家设计权申请已通过';
                        }
                        $add=new Bydletter();
                        $add->data([
                            'user_id'=>$row['user_id'],
                            'orderid'=>0,
                            'content'=>$content,
                            'zt'=>'签约结果',
                            'state'=>0
                        ]);
                        $add->save();
                        $user=\app\admin\model\BydUser::find($row['user_id']);
                        $tmpType = $row['sole_type']==0 ? '经营权' : '设计权';
                        $arr=[
                            'openid'=>$user['openid'],
                            'thing2'=>"您的美居独家".$tmpType."申请已通过",//$data['news'],
                            'thing6'=>"请前往小程序查看",
                        ];
                        $new=new News();
                        $news=$new->vr($arr);
                    }elseif($params['state']==2){
                        if($row['sole_type']==0){
                            $content='您的美居独家经营权申请已被驳回';
                            $update=\app\admin\model\SoleBuilding::where('id',$row['bid'])->update(['sign_bid'=>0]);
                        }else{
                            $update=\app\admin\model\SoleBuilding::where('id',$row['bid'])->update(['sign_did'=>0]);
                            $content='您的美居独家设计权申请已被驳回';
                        }
                        $add=new Bydletter();
                        $add->data([
                            'user_id'=>$row['user_id'],
                            'orderid'=>0,
                            'content'=>$content,
                            'zt'=>'签约结果',
                            'state'=>0
                        ]);
                        $add->save();
                        $user=\app\admin\model\BydUser::find($row['user_id']);
                        $arr=[
                            'openid'=>$user['openid'],
                            'thing2'=>"您的美居独家设计权申请已被驳回",//$data['news'],
                            'thing6'=>"请前往小程序查看",

                        ];
                        $new=new News();
                        $news=$new->vr($arr);
                    }
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 检测是否有新退货消息
     */
    public function isHaveNewAfter()
    {
        $cache=\think\Cache::get('sqsq');
        if(!empty($cache)){
            $tips = 'aftersale:tips:number';
            //edis = (new Redis())->getRedis();
            $tipsNumber = rand();
            $this->success('获取新申请消息数量成功', null, $tipsNumber);
        }

    }

    /**
     * 已确认新退货消息
     */
    public function handleTui()
    {
        $type = $this->request->post('type');
        $tips = 'aftersale:tips:number';
        $tipsNumber = rand();
        \think\Cache::rm('sqsq');
        $this->success('确认新申请消息成功', null, $type);
    }
}
